package prop;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class PropertiesReader extends Thread {
	private Properties prop;
	private long lastModified;
	private File file;
	
	private static PropertiesReader INSTANCE = new PropertiesReader("mapc.properties");
	
	public static PropertiesReader getInstance() {
		return INSTANCE;
	}
	
	public PropertiesReader(String config) {
		prop = new Properties();
		file = new File(config);
		if(!file.exists() || file.isDirectory()) {
			throw new IllegalArgumentException(config + " is not a correct file.");
		}
		
		lastModified = file.lastModified();
		try {
			getProperties().load(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		start();
	}
	
	public void run() {
		while(true) {
			long last = file.lastModified();
			
			if(last != lastModified) {
				lastModified = last;
				try {
					getProperties().load(new FileInputStream(file));
				} catch (FileNotFoundException e) {
					throw new RuntimeException(e);
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
		}
	}
	
	public synchronized String getStringProperty(String key) {
//		System.out.println(key + " = " + prop.getProperty(key));
		
		return prop.getProperty(key);
	}
	
	public synchronized int getIntegerProperty(String key) {
		int result;
		String property = prop.getProperty(key);
		if(property.equals("Integer.MAX_VALUE")) {
			result = Integer.MAX_VALUE;
		} else {
			result = Integer.parseInt(property);
		}
//		System.out.println(key + " = " + result);
		
		return result;
	}
	
	public synchronized double getDoubleProperty(String key) {
		double result;
		String property = prop.getProperty(key);
		if(property.equals("Double.MAX_VALUE")) {
			result = Double.MAX_VALUE;
		} else {
			result = Double.parseDouble(property);
		}
//		System.out.println(key + " = " + result);
		
		return result;
	}
	
	public synchronized Properties getProperties() {
		return prop;
	}
}
